from pdfrw import PdfReader, PdfWriter
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
import io

def add_signature_with_pdfrw(input_pdf, output_pdf, signature_img, x, y, width, height):
    # 读取原始PDF
    template = PdfReader(input_pdf)
    
    # 创建签名层
    packet = io.BytesIO()
    can = canvas.Canvas(packet, pagesize=letter)
    can.drawImage(signature_img, x, y, width, height)
    can.save()
    
    # 读取签名层
    packet.seek(0)
    overlay = PdfReader(packet)
    
    # 合并图层
    for page in template.pages:
        page.Merge(overlay.pages[0])
    
    # 输出结果
    PdfWriter().write(output_pdf, template)

file_path = "D:\\workspace\\个人文件"
pdf_file = "C:\\Users\\syske\\Documents\\未婚承诺书.pdf"
# 使用示例
add_signature_with_pdfrw(
    input_pdf=pdf_file,
    output_pdf="output.pdf",
    signature_img=f"{file_path}\\sign-leicao.png",
    x=100,       # 从左边的距离
    y=100,       # 从顶部的距离
    width=200,   # 签名宽度
    height=100   # 签名高度
)